<template>
  <div class="box">
    <SearchForm
      title="任务列表"
      :formInputs="searchFromInputs"
      :form="searchFrom"
      @clickSubmitForm="loadData"
    >
    </SearchForm>
    <div class="table">
      <a-button icon="plus" type="link" @click="actionClick('add')"
        >新建任务</a-button
      >
      <FormModal
        :formConfig="formModalConfig"
        :confirmLoading="confirmLoading"
        ref="submitForm"
        @submit="submitForm"
      />
      <a-table
        :columns="columns"
        :data-source="data"
        :rowKey="(record) => record.id"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <span slot="status" slot-scope="text">
          <a-tag :color="['volcano', 'green', 'geekblue'][text]">
            {{ status[text] }}
          </a-tag>
        </span>
        <a-space :size="10" slot="operation" slot-scope="text, record">
          <template>
            <a-popconfirm
              title="确定删除?"
              @confirm="actionClick('remove', record)"
            >
              <a><a-icon type="delete" /> 删除</a>
            </a-popconfirm>
            <a @click="actionClick('edit', record)"
              ><a-icon type="edit" /> 编辑</a
            >
            <a
              @click.prevent="
                () => {
                  $router.push({
                    path: '/project',
                    query: { id: record.id },
                  });
                }
              "
              ><a-icon type="info" /> 详情</a
            >
          </template>
        </a-space>
      </a-table>
    </div>
  </div>
</template>

<script>
import SearchForm from "../components/SearchForm";
import FormModal from "../components/FormModal";

const status = {
  0: "未开始",
  1: "进行中",
  2: "已完结",
};

const columns = [
  { title: "名称", dataIndex: "Title", key: "Title" },
  { title: "总金额", dataIndex: "TotalPrice", key: "TotalPrice" },
  {
    title: "开始时间",
    key: "StartDate",
    dataIndex: "StartDate",
  },
  {
    title: "结束时间",
    key: "EndDate",
    dataIndex: "EndDate",
  },
  {
    title: "机构",
    key: "Organization",
    dataIndex: "Organization",
  },
  {
    title: "地址",
    key: "Address",
    dataIndex: "Address",
  },
  {
    title: "联系人",
    key: "Contacter",
    dataIndex: "Contacter",
  },
  {
    title: "联系人电话",
    key: "Tel",
    dataIndex: "Tel",
  },
  {
    title: "状态",
    key: "Status",
    dataIndex: "Status",
    scopedSlots: { customRender: "status" },
  },
  {
    title: "操作",
    key: "operation",
    align: "center",
    width: 400,
    scopedSlots: { customRender: "operation" },
  },
];

// 弹出表单（新增/修改）
const formModalConfig = {
  title: "新建项目",
  items: [
    {
      name: "id",
      type: "hidden", //主键，放入隐藏域
    },
    {
      name: "Title",
      label: "项目名称",
      type: "input",
      rules: [{ required: true, message: `请输入项目名称` }],
    },
    {
      name: "TotalPrice",
      label: "总金额",
      type: "number",
    },
    {
      name: "StartDate",
      label: "开始时间",
      type: "datetime",
    },
    {
      name: "EndDate",
      label: "结束时间",
      type: "datetime",
    },
    {
      name: "Organization",
      label: "机构",
      type: "input",
    },
    {
      name: "Address",
      label: "地址",
      type: "input",
    },
    {
      name: "Contacter",
      label: "联系人",
      type: "input",
    },
    {
      name: "Tel",
      label: "联系人电话",
      type: "input",
    },
    {
      name: "Files",
      label: "附件",
      type: "upload",
    },
  ],
};

export default {
  data() {
    return {
      loading: false,
      status,
      columns,
      pagination: {
        pageSize: 10,
        current: 1,
      },
      searchFrom: {
        name: "",
      },
      searchFromInputs: [
        {
          model: "name",
          label: "名称",
          type: "input",
        },
      ],
      data: [],
      users: [],
      formModalConfig,
      confirmLoading: false,
    };
  },
  mounted() {
    this.loadData();
  },
  computed: {
    user() {
      return this.$store.getters.user;
    },
  },
  methods: {
    handleTableChange(pagination) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.loadData();
    },
    getData(params = {}) {
      this.loading = true;
      this.$myaxios.get(`/project/list`, { params }).then((response) => {
        this.loading = false;
        const result = response.data;
        if (result) {
          const { success, data, msg } = result;
          if (success) {
            const { list, totalCount } = data;
            this.data = list;
            const pagination = { ...this.pagination };
            pagination.total = totalCount;
            this.pagination = pagination;
          } else {
            this.$message.error(msg);
          }
        } else {
          this.$message.error("获取项目列表失败");
        }
      });
    },
    loadData() {
      this.getData({
        ...this.searchFrom,
        page: this.pagination.current,
        size: this.pagination.pageSize,
      });
    },
    actionClick(action, item = {}) {
      if (action === "add") {
        this.$refs.submitForm.handleOpenForm();
      } else if (action === "edit") {
        this.$refs.submitForm.handleOpenForm(item);
      } else if (action === "remove") {
        this.$myaxios
          .delete("/project", { params: { id: item.id } })
          .then((res) => {
            const result = res.data;
            if (result) {
              const { success, msg } = result;
              if (success) {
                this.$message.success("删除成功");
                this.loadData();
              } else {
                this.$message.error(msg);
              }
            }
          });
      }
    },
    submitForm(values) {
      let action = null;
      let method;
      if (values.id) {
        action = "/project/" + values.id;
        method = "PUT";
      } else {
        action = "/project";
        method = "POST";
      }

      const formData = new FormData();
      for (const prop in values) {
        const v = values[prop];
        if (v) {
          if (v.fileList) {
            v.fileList.forEach((file) => {
              if (file instanceof File) {
                formData.append(prop, file, file.fileName);
              }
            });
          } else {
            formData.append(prop, v);
          }
        }
      }

      this.$myaxios({
        method,
        url: action,
        data: formData,
      }).then((res) => {
        const result = res.data;
        if (result) {
          const { success, msg } = result;
          if (success) {
            this.$refs.submitForm.visible = false;
            this.$message.success("项目信息提交成功");
            this.loadData();
          } else {
            this.$message.error(msg);
          }
        }
      });
    },
  },
  components: {
    SearchForm,
    FormModal,
  },
};
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .table {
    flex: 1;
    background-color: white;
    padding: 10px 10px 0 10px;
    text-align: right;
  }
}
</style>
